#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include "stock.h"
#include "llist.h"


//创建链表
LLIST * llist_create(int size){
	LLIST *new;
	new = malloc(sizeof(*new));

	if(new == NULL){
		printf("err\n");
		return NULL;
	}

	new->size=size; 
	new->head.prev=new->head.next=&new->head;
	return new;
}


//新增节点
int llist_insert(LLIST *ptr,const void *data){
	struct llist_node *newnode;
	
	newnode=malloc(sizeof(*newnode)+ptr->size);

	if(newnode==NULL){
		perror("insert");
		return -1;
	}
	memcpy(newnode->data,data,ptr->size);
	newnode->prev=ptr->head.prev;
	newnode->next=&ptr->head;
	newnode->prev->next=newnode;
	newnode->next->prev=newnode;
	return 0;
}

static void * find__(LLIST *ptr,const void *key,int (*cmp)(const void *,const void *)){
	struct llist_node *cur;
	for(cur=ptr->head.next;cur!=&ptr->head;cur=cur->next){
		if(cmp(key,cur->data)==0){
			break;
		}
	}
	return cur;
}
void * llist_find(LLIST *ptr,const void *key,int (*cmp)(const void *,const void *)){
	struct llist_node *cur;
	cur=find__(ptr,key,cmp);
	if(cur==&ptr->head){
		return NULL;
	}
	return cur->data;
}

int llist_delete(LLIST *ptr,const void *key,int (*cmp)(const void *, const void * )){
	struct llist_node *cur;
	cur=find__(ptr,key,cmp);
	if(cur!=&ptr->head){
		cur->prev->next=cur->next;
		cur->next->prev=cur->prev;
		free(cur);
		return 0;
	}
	return -1;
}
void llist_travel(LLIST *ptr,void (*llist_op)(void *))
{
	struct llist_node *cur;
	for(cur=ptr->head.next;cur!=&ptr->head;cur=cur->next)
	{
		llist_op(cur->data);
	}
}
void llist_destroy(LLIST *ptr)
{
	struct llist_node *cur,*save;
	for(cur=ptr->head.next;cur!=&ptr->head;cur=save)
	{
		save=cur->next;
		free(cur);
	}
	free(ptr);
}

